--
-- Author: shunguo.chen
-- Date: 2017-12-26 18:46:25
--
-- PvpController
--

local PvpView = import("..views.PvpView")
local PvpLoadingView = import("..views.PvpLoadingView")
local PvpVSView = import("..views.PvpVSView")
local PvpBookView = import("..views.PvpBookView")
local PvpDuelBookView = import("..views.PvpDuelBookView")
local PvpDuelTeamView = import("..views.PvpDuelTeamView")
local PvpDuelRecordView = import("..views.PvpDuelRecordView")
local PvpDuelFightEndFailedView = import("..views.PvpDuelFightEndFailedView")
local PvpDuelFightEndWinView = import("..views.PvpDuelFightEndWinView")
local PvpLevelView = import("..views.PvpLevelView")
local PvpRewardView = import("..views.PvpRewardView")
local PvpMatchView = import("..views.PvpMatchView")
local PvpWinView = import("..views.PvpWinView")
local PvpFailView = import("..views.PvpFailView")
local PvpChampionWinView = import("..views.PvpChampionWinView")
local PvpChampionFailView = import("..views.PvpChampionFailView")
local BattleFailedView = require("app.system.battlefailed.BattleFailedView")
local PvpChallengeFailView = import("..views.PvpChallengeFailView")
local PvpChallengeActivitySuccessView = import("..views.PvpChallengeActivitySuccessView")
local PvpChallengeRankAwardView = import("..views.PvpChallengeRankAwardView")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(params)
	self.super.ctor(self, params)

end

function ClassRef:init()
	self._model = app:getInst("PvpModel")
	self._teamModel = app:getInst("TeamModel")

	self._walletHandler = UD:onChanged("wallet", handler(self, self.updatePlayer))
	-- PvpView cache
	self._view = nil

	-- 打开胜利界面的计数，两次计数才打开
	self._winNum = 0
	-- 缓存胜利的奖励
	self._winRewards = nil
	-- 缓存胜利界面的回调
	self._winCB = nil
	-- 缓存胜利原因
	self._winReason = nil

	-- 打开失败界面的计数，两次计数才打开
	self._failNum = 0
	-- 缓存失败的描述
	self._failStrs = nil
	-- 缓存失败界面的回调
	self._failCB = nil
	-- 缓存失败原因
	self._failReason = nil

	-- loadingView cache
	self._loadingView = nil
	-- 挑战赛结算标记
	self._challengeFlag = false
	self._challengeResultData = {}

end

function ClassRef:setChampionForceOpen()
	self._championForceOepn = true
end

function ClassRef:isChampionForceOpen()
	return self._championForceOepn
end

function ClassRef:removeListeners()
	self.super.removeListeners(self)
	UD:unChanged("wallet", self._walletHandler)
end

function ClassRef:listEvent()
	return {
		"onLoadingUp",
		"OnGameConnected",
		"onDailyUpdate",
		"onMapChanged",
		"onReconnectSuccessed",
		"onLoginedNoticeOver",
	}
end

function ClassRef:onEvent(eventName, ...)
	if eventName == "onLoadingUp" then
		self:updateMyLoadingView(...)
	elseif eventName == "onMapChanged" then
		local firstIntoMap = ...
		if firstIntoMap then
			-- self._model:reqPvpInfo()
			self._model:reqChampionSeasonInfo()
		end
		self._model:onMapChanged()
	elseif eventName == "OnGameConnected" then
		-- self._model:reqPvpInfo()
		-- self._model:reqChampionSeasonInfo()
	elseif eventName == "onDailyUpdate" then
		-- self._model:reqPvpInfo()
		self._model:reqChampionSeasonInfo()
	elseif eventName == "onReconnectSuccessed" then
		-- self._model:reqPvpInfo()
	elseif eventName == "onLoginedNoticeOver" then
		self._model:checkBattleMatch()
	end
end

-- data = panel index
-- param = 额外参数(目前只在data=1时有用，非nil表示显示当前目标的tips)
function ClassRef:openView(data, param)
	-- 跨服副本中，不能进入精英赛
	if DungeonManager:isCrossDungeon() then
	    display.pushToast(L("CrossServerTips26"))
	    return
	end

	if cc.isDead(self._view) then
		self._view = PvpView.new(app.mvc.VIEWTYPE_BLUR)
		self._view:onCloseView(handler(self, self.closeView))
		self._view:onClearView(handler(self, self.clearView))
		self._view:onOperate(handler(self, self.onOperate))
		self._view:onSwitchPanel(handler(self, self.onSwitchPanel))
	end
	self:addChild(self._view, data)

	local index = data or 1
	self._view:show(index)
	if index == 1 and param then
		self._view:isShowTips(true)
	end

	self:updateChampionRedPoint()
end

-- info = PvpLoadingInfo
function ClassRef:openLoadingView(info)
	-- 现在加载界面用的是 AreanaVs, 这里现在好像不用了?? TODO？？
	if not self._loadingView then
		local view = PvpLoadingView.new()
		view:onClearView(function() self._loadingView = nil end)
		view:onOperate(function(op)
			if op == "timeout" then
				-- 超时模拟结束
				self._model:S2C_PVPLoadingClose()
			end
		end)
		UIHandler:addChildToUiParent(view, SceneZOrder.loadingZOrder + 1)
		self._loadingView = view
	end

	self._loadingView:refresh(info)
	self._loadingView:show()
end
-- datas = {{uid=, progress=}, ...}
function ClassRef:updateLoadingView(datas)
	if self._loadingView then
		self._loadingView:updatePg(datas)
	end
end
-- 更新自己的进度，使用loading的数据
-- pg 百分比
function ClassRef:updateMyLoadingView(pg)
	if self._loadingView then
		self._loadingView:updateMyPg(pg)
	end
end
function ClassRef:closeLoadingView(datas)
	if self._loadingView then
		self._loadingView:removeFromParent()
		self._loadingView = nil
	end
end

-- cell = UserBaseInfo/AvatarParams
-- infos={{cell, ...}, {cell, ...}, {myName, enemyName}}
function ClassRef:openVSView(infos)
	local view = PvpVSView.new()
	UIHandler:addPopupUi(view, view:getViewName())
	view:onCloseView(function(sender)
		UIHandler:removePopupUiByKey(sender:getViewName())
	end)

	view:refresh(infos)
	view:show()
end

-- 打开pvp Book
function ClassRef:openBookView(teamTarget)
	local view = PvpBookView.new(app.mvc.VIEWTYPE_BLUR)
	view:onCloseView(function(sender)
		self:removeChild(sender)
    end)
    view:onOperate(handler(self, self.onOperate))
    view:refresh(self._model:getPvpInfo(), teamTarget)
    self:addChild(view)
    view:show()
end

-- season = PvpSeasonInfo
-- type = 1(升级) 2（降级）3（赛季等级）
function ClassRef:openLevelView(season, type)
	local view = PvpLevelView.new()
	view:onCloseView(function(sender)
		if type == 3 then
			app:sendMsg("BoxController", "openView", {boxType = Enums.BoxType.championSeason, seasonLv = season.lv})
		end
    	UIHandler:removePopupUiByKey(sender:getViewName())
    	self:_checkLabberGuide()
    end)
    view:refresh(season, type)
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end

function ClassRef:_checkLabberGuide()
	if not self:isViewVisible() then return end

	self._view:checkLabberGuide()
end

function ClassRef:openRewardView(seasonLv)
	local view = PvpRewardView.new()
	view:onCloseView(function(sender)
    	UIHandler:removePopupUiByKey(sender:getViewName())
    end)
	view:onOperate(function(op, params)
        if op == "openBox" then
        	self._model:reqSessionReward()
        end
    end)
    view:refresh(seasonLv)
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end

function ClassRef:openMatchView(maxSeconds, curSeconds)
	-- 模拟点击停止，其他的方法没找到
	app:getLaunchCtl():endCharacterMove()

	local viewName = PvpMatchView:getViewName()
	local view = UIHandler:getPopupUiByKey(viewName)
	if not view then
		view = PvpMatchView.new()
		view:onCloseView(function(sender)
	    	UIHandler:removePopupUiByKey(sender:getViewName())
	    end)
		view:onClearView(function()
			self._model:clearPvpMatch()
	    end)
	    view:onOperate(function(op, params)
		    	if op == "cancel" then
		    		self._model:reqPvpCancel()
		    	end
	    	end)
	    UIHandler:addPopupUi(view, view:getViewName())
	end
    local pvpMatchingEnabled = app:sendMsg("TeamModel", "pvpMatchingEnabled")
    view:refresh(maxSeconds, curSeconds, pvpMatchingEnabled)
    view:show()

	app:sendMsg("NewTeamReadyAndSettingController", "closeView")
end

function ClassRef:closeMatchView()
	local view = UIHandler:getPopupUiByKey(PvpMatchView:getViewName())
	if view then
		view:closeView()
	end
end

-- 需要两个条件达成才会打开界面，
-- 1.战斗结束奖励消息（包含奖励） rewards~=nil, cb=nil
-- 2.战斗mvp动画结束（包含cb，用来关闭mvp动画）cb~=nil, rewards=nil
function ClassRef:openWinView(rewards, cb, reason)
	if self._challengeFlag then 
		self._winNum = 1
		local data = self._challengeResultData
		self:openChallengeResultView(data.type, data.isWon, data.rewards, data.grade, data.score, data.dailyScore, data.winTimes)
		return
	end

	-- 跨服副本中忽略收到的胜利失败消息
	if DungeonManager:isCrossDungeon() then
		print("isCrossDungeon can't show PvpWinView")
		return
	end

	self._winNum = self._winNum + 1
	print("PvpController.openWinView", self._winNum)
	if self._winNum < 2 then
		if rewards then
			self._winRewards = rewards
		end
		if cb then
			self._winCB = cb
		end
		if reason then
			self._winReason = reason
		end
	else
		local view = PvpWinView.new()
		view:onCloseView(function(sender)
			executeFunc(cb or self._winCB)
		    self._winCB = nil
	    	UIHandler:removePopupUiByKey(sender:getViewName())
	    end)
	    view:refresh(rewards or self._winRewards, reason or self._winReason)
	    UIHandler:addPopupUi(view, view:getViewName())
	    view:show()

	    -- 清除缓存的数据
		self._winNum = 0
	    self._winRewards = nil
	    self._winReason = nil
	end
end

-- 同胜利
function ClassRef:openFailView(strs, cb, reason)
	if self._challengeFlag then 
		self._failNum = 1
		local data = self._challengeResultData
		self:openChallengeResultView(data.type, data.isWon, data.rewards, data.grade, data.score, data.dailyScore, data.winTimes)
		return 
	end

	-- 跨服副本中忽略收到的胜利失败消息
	if DungeonManager:isCrossDungeon() then
		print("isCrossDungeon can't show PvpFailView")
		return
	end

	self._failNum = self._failNum + 1
	if self._failNum < 2 then
		if strs then
			self._failStrs = strs
		end
		if cb then
			self._failCB = cb
		end
		if reason then
			self._failReason = reason
		end
	else
		local view = PvpFailView.new()
		view:onCloseView(function(sender)
			executeFunc(cb or self._failCB)
		    self._failCB = nil
	    	UIHandler:removePopupUiByKey(sender:getViewName())
	    end)
	    view:refresh(strs or self._failStrs, reason or self._failReason)
	    UIHandler:addPopupUi(view, view:getViewName())
	    view:show()

	    -- 清除缓存的数据
		self._failNum = 0
	    self._failStrs = nil
	    self._failReason = nil
	end
end

-- 挑战赛结果返回
function ClassRef:openChallengeResultView(type, isWon, rewards, grade, score, dailyScore, winTimes)
	self._challengeFlag = true

	-- pvp玩法，要等到mvp界面展示完，再显示结算界面
	if type == Enums.TeamTarget.arena or type == Enums.TeamTarget.melee or type == Enums.TeamTarget.theatre 
		or type == Enums.TeamTarget.eliteMatchArena then
		if self._winNum == 0 and self._failNum == 0 then
			local data = {}
			data.type = type
			data.isWon = isWon
			data.rewards = rewards
			data.grade = grade
			data.score = score
			data.dailyScore = dailyScore
			data.winTimes = winTimes
			self._challengeResultData = data
			return 
		end	
	end

	-- 清除缓存的数据
	self._winNum = 0
	self._winRewards = nil
	self._winReason = nil
	self._failNum = 0
	self._failStrs = nil
	self._failReason = nil

	local function executeCB()
        MapManager:setNextChangeMapIgnoreAni(true)
        app.session:request("pb_map.C2S_BackToLastMap",{})

        app:dispatchEvent({name="EVENT_BATTLE_PVP_END"})
        
		MapManager:setChangeMapOverCB(function()
			if type == Enums.TeamTarget.eliteMatchArena then
	            app:sendMsg("PvpController", "openView" )
				app:sendMsg("PvpEliteController", "onEliteMatchInfoUpdate")
			else
				app:sendMsg("PvpChallengeController", "openView")
			end
        end)
	end

	local function executeCB2()
		app.session:request("pb_map.C2S_BackToLastMap",{})
		MapManager:setChangeMapOverCB(function()
            app:sendMsg("PvpChallengeController", "openView")
        end)
	end

	-- 把rewards里面的itemData提了出来
	local itemDatas = {}
	for i, reward in ipairs(rewards) do
		itemDatas[i] = reward.itemData
	end

	local view 
	if isWon then
		-- 活动类型的单独处理 （决斗之王 和 星空谜棋）
		if type == Enums.TeamTarget.kof or type == Enums.TeamTarget.chess then
			view = PvpChallengeActivitySuccessView.new()
			view:refreshContent(type, grade, score, itemDatas, dailyScore, winTimes)
		else
			view = PvpWinView.new()
	   		view:refresh(rewards, nil, type, dailyScore, winTimes)
		end
	else
		if type == Enums.TeamTarget.eliteMatchArena then
			view = BattleFailedView.new()
		else
			view = PvpChallengeFailView.new()
			view:refresh("", itemDatas, type, dailyScore, winTimes)

			view:showActivityNotice(type, score)
		end
	end

	-- 设置回调函数
	local cb = executeCB
	if type == Enums.TeamTarget.kof or type == Enums.TeamTarget.chess then
		cb = executeCB2
	end

	view:onCloseView(function(sender)
		-- TODO 是否再来一局
		-- local createTeamDialog = display.newConfirmDialog(L("是否再来一局？"), function()
		-- 	self._model:reqChallengeOneMoreGame(true)
		-- 	executeCB()
		-- end, function()
		-- 	self._model:reqChallengeOneMoreGame(false)
		-- 	executeCB()
		-- end)
		-- UIHandler:addPopDialog( createTeamDialog )
		cb()
	    UIHandler:removePopupUiByKey(sender:getViewName())
	end)
	UIHandler:addPopupUi(view, view:getViewName())
	view:show()

end

-- 冠军赛成功
function ClassRef:openChampionWinView(data, cb)
	self._winNum = self._winNum + 1
	print("PvpController.openChampionWinView", self._winNum)

	if self._winNum < 2 then
		self._winData = data
		self._winCB = cb
	else
		local view = PvpChampionWinView.new()
		view:onCloseView(function()
			executeFunc(cb or self._winCB)
		    self._winCB = nil
	    	view:removeFromParent()
	    end)
	    view:refresh(data or self._winData)
	    UIHandler:addPopupUi(view)
	    view:show()

	    -- 清除缓存的数据
		self._winNum = 0
		self._winData = nil
	end
end

-- 冠军赛失败
function ClassRef:openChampionFailView(data, cb)
	self._failNum = self._failNum + 1
	print("PvpController.openChampionFailView", self._failNum)

	if self._failNum < 2 then
		self._failData = data
		self._failCB = cb
	else
    	local view = PvpChampionFailView.new()
    	view:onCloseView(function()
    		executeFunc(cb or self._failCB)
    		self._failCB = nil
    		view:removeFromParent()
    	end)
    	view:refresh(data or self._failData)
    	UIHandler:addPopupUi(view)
    	view:show()

    	-- 清除缓存的数据
		self._failNum = 0
		self._failData = nil
	end
end

-- 立即打开Chess胜利界面
-- rewards = 奖励
function ClassRef:openChessWinView(rewards)
	local view = PvpWinView.new()
	view:onCloseView(function(sender)
		UIHandler:removePopupUiByKey(sender:getViewName())
	end)
	view:refresh(rewards)
	UIHandler:addPopupUi(view, view:getViewName())
	view:show()
end

-- 立即打开Chess失败界面
-- str = 失败信息
function ClassRef:openChessFailView(str)
	local view = PvpFailView.new()
	view:onCloseView(function(sender)
		UIHandler:removePopupUiByKey(sender:getViewName())
	end)
	view:refresh(str)
	UIHandler:addPopupUi(view, view:getViewName())
	view:show()
end


---------------------------------------------------------------
-- kof 结果
function ClassRef:S2C_KingOfDuelResult(msg)
	-- dump(msg, "S2C_KingOfDuelResult")
	-- loading中就失败，说明是超时导致的失败
	if app:sendMsg("PvpModel", "isInPvpLoading") and msg.result == "LOSE"then
		-- 模拟关闭loading界面并调用C2S_BackToLastMap
		display.pushToast(L("OtherPlayerRun"))
		app:sendMsg("PvpModel", "S2C_PVPLoadingClose")
		app.session:request("pb_map.C2S_BackToLastMap",{})
	end
end

function ClassRef:onOpenBox(pvpInfo)
	local view = UIHandler:getSystemUi():getUIByKey(PvpBookView:getViewName())
	if view then
		view:refreshPvpInfo(pvpInfo)
	end

	if not self:isViewAlive() then return end
	self._view:refreshLadder(pvpInfo)
end


-- pvpInfo更新
function ClassRef:onPvpInfoUpdate(pvpInfo)
	-- if not self:isViewAlive() then return end
	-- if self._curId ~= 1 then return end
	-- --self._view:refreshLadder(pvpInfo)
	-- local openLvDict = self._teamModel:getTargetTypeOpenLvDict(Enums.TeamMatchType.Pvp)
	-- self._view:updateLabberView(self._model:getPvpInfo(), openLvDict)
end

-- championSeasonInfo更新
function ClassRef:onChampionInfoUpdate(seasonInfo)
	if not self:isViewAlive() then return end
	if self._curId ~= 2 then return end

	self._view:refreshChampion(seasonInfo)
end

------------------------------------------------------------
function ClassRef:onOperate(operate, param)
	-- print("PvpController:onOperate operate = " .. operate)
	if operate == "openBox" then
		local params = {boxType=Enums.BoxType.pvp}
		app:sendMsg("BoxController", "openView", params)
	elseif operate == "openChampionBox" then
		local params = {boxType=Enums.BoxType.champion, championType=param}
		app:sendMsg("BoxController", "openView", params)
	elseif operate == "openLevelView" then
		self:openLevelView(param.info, param.type)

	elseif operate == "refreshDuelOpponent" then
		--刷新对手
        dump(param,"refreshDuelOpponent")
        self._model:reqDuelRefreshEnemy(param)
    elseif operate == "openDuelBookView" then
        self:onOpenDuelBookView()
    elseif operate == "openRankAwardView" then
        --打开排行奖励界面
        self:openChallengeRankAward(param.playId)
	elseif operate == "openDuelTeamView" then
		self:openPvpDuelTeamView()
	elseif operate == "openDuelRecordView" then
		--此处要先向服务器请求战斗记录数据
		self._model:reqDuelFightRecord()
	elseif operate == "changeDuelPartnerStatus" then
		--改变随从的上阵状态
		--dump(param,"changeDuelPartnerStatus")
		self._model:reqDuelOnBattlePartner(param.partnerId, param.isOnBattle)
    elseif operate == "buyDuelFightNum" then
        --判断钻石足够不 不够则跳转到商店
        local costDaibi = UD:parseRewardToBagItem(GD:getSystemStrPar("duelGamePlayPrice"))
        if UD:getDaibiValue(costDaibi:getId()) >= costDaibi:getAmount() then
            self._model:reqBuyDuelFightNum()
        else
            app:sendMsg("MallController", "openNeedPayDialog")
        end
    elseif operate == "startDuelFight" then
        --dump(param,"startDuelFight")

		--判断玩家是否在副本里面
		if DungeonManager:isInDungeon() then
			display.pushToast(L("lua_code_text_206"))
		else
			--判断玩家是否没有队伍 或者 队伍只有自己一个人才可以战斗
			if app:sendMsg("TeamModel", "isSingle") then
				self._model:reqStartDuelFight(param)
			else
				display.pushToast(L("duelGametips41"))
			end
		end
	end
end

function ClassRef:removeDuelPartner(partnerId)
	self._model:reqDuelOnBattlePartner(partnerId, false)
end

-- 1 精英赛
-- 2 冠军赛
-- 2 决斗赛
function ClassRef:onSwitchPanel(id)
	self._curId = id

	if id == 1 then
		UD.csEliteMatch:C2S_GetCrossCombatInfo()
	elseif id == 2 then
		-- 拉取最新的冠军赛数据
		self._model:reqChampionSeasonInfo() 
	elseif id == 3 then
		--获取决斗赛信息
		self._model:reqDuelInfo()
	end

end

--显示决斗赛说明界面
function ClassRef:onOpenDuelBookView()
	if cc.isDead(self._duelBookView) then
		self._duelBookView = PvpDuelBookView.new(app.mvc.VIEWTYPE_BLUR)
		self._duelBookView:onCloseView(handler(self, self.closeDuelBookView))
		self._duelBookView:onClearView(handler(self, self.clearDuelBookView))
		self._duelBookView:onOperate(handler(self, self.onOperate))
	end
	self:addChild(self._duelBookView)
	self._duelBookView:show()
end

function ClassRef:closeDuelBookView()
	if not cc.isDead(self._duelBookView) then
		self:removeChild(self._duelBookView)
	end
end

function ClassRef:clearDuelBookView()
	if self._duelBookView then
		self._duelBookView = nil
	end
end

--显示决斗赛随从上阵界面
function ClassRef:openPvpDuelTeamView()
	if cc.isDead(self._duelTeamView) then
		--此处要传入数据为已上阵的partner id
		self._duelTeamView = PvpDuelTeamView.new(app.mvc.VIEWTYPE_BLUR, self._model:getDuelInfo())
		self._duelTeamView:onCloseView(handler(self, self.closeDuelTeamView))
		self._duelTeamView:onClearView(handler(self, self.clearDuelTeamView))
		self._duelTeamView:onOperate(handler(self, self.onOperate))
	end
	self:addChild(self._duelTeamView)
	self._duelTeamView:show()

    UD:saveGeneric("duelChangePartner",true)
end

function ClassRef:closeDuelTeamView()
	if not cc.isDead(self._duelTeamView) then
		self:removeChild(self._duelTeamView)
	end
end

function ClassRef:clearDuelTeamView()
	if self._duelTeamView then
		self._duelTeamView = nil
	end
end

--决斗赛比赛记录界面
function ClassRef:openPvpDuelRecordView(data)
	if cc.isDead(self._duelRecordView) then
		--此处要传入数据为已上阵的partner id
		self._duelRecordView = PvpDuelRecordView.new(app.mvc.VIEWTYPE_BLUR,data)
		self._duelRecordView:onCloseView(handler(self, self.closeDuelRecordView))
		self._duelRecordView:onClearView(handler(self, self.clearDuelRecordView))
		self._duelRecordView:onOperate(handler(self, self.onOperate))
	end
	self:addChild(self._duelRecordView)
	self._duelRecordView:show()
end

function ClassRef:closeDuelRecordView()
	if not cc.isDead(self._duelRecordView) then
		self:removeChild(self._duelRecordView)
	end
end

function ClassRef:clearDuelRecordView()
	if self._duelRecordView then
		self._duelRecordView = nil
	end
end

-- 决斗赛排行奖励
function ClassRef:openChallengeRankAward(rankId)
	local view = PvpChallengeRankAwardView.new()
	view:onCloseView(function()
		UIHandler:removePopupUiByKey(view:getViewName())
	end)
	view:onOperate(handler(self, self.onOperate))
	UIHandler:addPopupUi(view, view:getViewName())
	view:updateViewByRankId(rankId)
	view:show()
end

--收到刷新消息刷新决斗赛界面
--{myInfo = duelMyInfo, enemyList = opponentInfos }
function ClassRef:refreshPvpDuelView(msg)
	if not self:isViewAlive() then return end
	if self._curId ~= 3 then return end

	self._view:updateDuelView(msg)
end


---决斗赛结束界面 胜利或者失败
function ClassRef:openDuelFightEndWin(data)
	local view
	if data.win then
		view = PvpDuelFightEndWinView.new(nil,data)
	else
		view = PvpDuelFightEndFailedView.new(nil,data)
	end

	view:onCloseView(function()
		UIHandler:removePopupUiByKey(view:getViewName())
		MapManager:setNextChangeMapIgnoreAni(true)
		app.session:request("pb_map.C2S_BackToLastMap",{})

		MapManager:setChangeMapOverCB(function()
			app:sendMsg("PvpController", "openView",3)
		end)
	end)
	view:onOperate(handler(self, self.onOperate))
	UIHandler:addPopupUi(view, view:getViewName())
	view:show()
end

----------------

-- 进入战斗时，清空结算数据
function ClassRef:clearPvpResultData()
	-- 打开胜利界面的计数，两次计数才打开
	self._winNum = 0
	-- 缓存胜利的奖励
	self._winRewards = nil
	-- 缓存胜利界面的回调
	self._winCB = nil
	-- 缓存胜利原因
	self._winReason = nil

	-- 打开失败界面的计数，两次计数才打开
	self._failNum = 0
	-- 缓存失败的描述
	self._failStrs = nil
	-- 缓存失败界面的回调
	self._failCB = nil
	-- 缓存失败原因
	self._failReason = nil

	self._winData = nil
	self._failData = nil

	-- 挑战赛结算标记
	self._challengeFlag = false
	self._challengeResultData = {}
end


-- 更新锦标赛的红点
function ClassRef:updateChampionRedPoint()
	-- 更新主界面红点
	UD.redPoint:checkStateByKey(RedPointConstant.Pvp_ChampionBox)

	-- 界面正在打开，更新页签的红点
	if self:isViewAlive() then
		self._view:refreshChampionPageRedPoint(self._model:getChampionInfo())
	end
end

function ClassRef:updatePlayer(name, old, new)
	if name == "arenaLuckBox" or name == "starPoint" then
		if self:isViewAlive() and self._curId == 1 then
	        self._view:refreshPvpBoxInfo()
	    end
	end
end

function ClassRef:showDuelRankChangeTips(num)
	UIHandler:showThirdLevelTips( { remindId = Constant.FUNC_TYPE_DUEL, params = {rankChange = num} } )
end

return ClassRef
